package cn.ivicar.sms.service.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SchemeRegistryFactory;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.carsmart.exception.CarsmartException;

public class HttpClientUtil {
	private static transient final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtil.class);

	private static final int MAX_CONNECTIONS = 100;
	private static final int MAX_CONNECTIONS_PER_ROUT = 100;
	/** 请求超时 **/
	private static final int CONNECTIONTIMEOUT = 5000;
	/** 等待数据超时 **/
	private static final int SOTIMEOUT = 5000;

	private static HttpClient httpClient;

	public static HttpClient getHttpClient() {
		return httpClient;
	}

	static {
		LOGGER.debug("开始初始化HttpCient...");
		init();
		LOGGER.debug("完成HttpClient初始化");
	}

	public static void init() {
		HttpParams params = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(params, CONNECTIONTIMEOUT);
		HttpConnectionParams.setSoTimeout(params, SOTIMEOUT);
		params.setIntParameter("http.conn-manager.max-total", MAX_CONNECTIONS);
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		SchemeRegistry schemeRegistry = SchemeRegistryFactory.createDefault();
		ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
		cm.setMaxTotal(MAX_CONNECTIONS);
		cm.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUT);
		httpClient = new DefaultHttpClient(cm, params);
	}

	public static byte[] getRemoteImage(String url) throws CarsmartException {
		try {
			HttpGet httpGet = new HttpGet(url);
			HttpResponse httpResponse = httpClient.execute(httpGet);
			HttpEntity entity = httpResponse.getEntity();

			return EntityUtils.toByteArray(entity);
		} catch (Exception ex) {
			LOGGER.info(String.format("请求失败 URL:[%s], ErrorMsg:[%s]", url, ex));
		}
		return null;
	}

}
